﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CarExam
{
    public partial class Frm_Main : Form
    {
        #region 自定义变量

        BLL.ItemBank _ib = new BLL.ItemBank();
        BLL.UserBLL _userbll = new BLL.UserBLL();
        Model.UserInfo _uis = new Model.UserInfo();
        Timer tmr = new Timer();

        DataTable dt_log;
        DataTable dt_tiku;
        //DataTable dt_cuoti;
        int qIndex = 0;//正在显示的题的索引
        string thisanswer;//正在显示题的正确的答案
        DataTable dt_using;//正在使用的题库
        int itemcount = 0;
        bool isanswer = false;
        float rate = 0;
        DateTime totaltime;

        List<string> ks_btn_name = new List<string>();
        string ks_btn_now;
        string ks_btn_defore;

        #endregion

        #region 窗体事件
        public Frm_Main(Model.UserInfo _ui)
        {
            InitializeComponent();
            itemcount = new BLL.ItemBank().GetItemBankCount();
            int num = Common.GenNum.GetNum(10);
            //if (itemcount - num < 100)//数据填充完成以后记得将3改为100
            //    num = num - (itemcount - num) < 0 ? 1 : itemcount - (itemcount - num);
            dt_tiku = _ib.GetItemBank(1, num);
            _uis = _ui;
            this.lab_tishi.Text = string.Format("欢迎考生：{0},快去选择考试模式进行考试或者练习吧", _uis.Realname);

            dt_log = new DataTable();
            dt_log.Columns.Add("tid");
            dt_log.Columns.Add("ZXDA");
            dt_log.Columns.Add("isOK");

        }

        /// <summary>
        /// 窗体加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Frm_Main_Load(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 窗体关闭事件
        /// </summary>
        private void Frm_Main_FormClosed(object sender, FormClosedEventArgs e)
        {
            bool res = _userbll.UpdateIsLocked(_uis.Uid);
            Application.Exit();
        }

        #endregion

        #region 按钮事件

        /// <summary>
        /// 清除错题库
        /// </summary>
        private void button8_Click(object sender, EventArgs e)
        {
            int res = _ib.ClearErrorItem();
            if (res == 1)
                MessageBox.Show("错题库清理完成！");
            else if (res != 1)
                MessageBox.Show("错题库清理过程出现错误，请重新操作！");
        }

        /// <summary>
        /// 上一题
        /// </summary>
        private void button6_Click(object sender, EventArgs e)
        {
            BeforeQuestion();
        }

        /// <summary>
        /// 下一题
        /// </summary>
        private void button7_Click(object sender, EventArgs e)
        {
            NextQuestion();
        }

        /// <summary>
        /// 退出按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button5_Click(object sender, EventArgs e)
        {
            bool res = _userbll.UpdateIsLocked(_uis.Uid);
            Application.Exit();
        }

        /// <summary>
        /// 顺序练习
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            this.d_time.Visible = false;
            this.label1.Visible = true;
            this.label2.Visible = true;
            this.btn_OK.Visible = false;
            panel5.Controls.Clear();

            dt_log.Clear();
            qIndex = 0;
            this.lab_tishi.Text = string.Format("考生：{0} 你好,你选择了顺序练习模式", _uis.Realname);
            dt_using = new DataTable();
            dt_using = dt_tiku;
            DisplayQuestion(dt_tiku);
        }

        /// <summary>
        /// 随即练习
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            this.d_time.Visible = false;
            this.label1.Visible = true;
            this.label2.Visible = true;
            this.btn_OK.Visible = false;
            dt_log.Clear();
            panel5.Controls.Clear();
            this.lab_tishi.Text = string.Format("考生：{0} 你好,你选择了随即练习模式", _uis.Realname);
            dt_using = new DataTable();
            qIndex = 0;
            int[] a = new int[100];//已经出现过的随机数
            GetItem(a);
            DisplayQuestion(dt_using);
        }

        /// <summary>
        /// 错题练习
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            this.d_time.Visible = false;
            this.label1.Visible = true;
            this.label2.Visible = true;
            this.btn_OK.Visible = false;
            dt_log.Clear();
            panel5.Controls.Clear();
            qIndex = 0;
            this.lab_tishi.Text = string.Format("考生：{0} 你好,你选择了错题练习模式", _uis.Realname);
            dt_using = new DataTable();
            dt_using = _ib.GetErrorItem(_uis.Uid);
            DisplayQuestion(dt_using);
        }

        /// <summary>
        /// 模拟考试
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button4_Click(object sender, EventArgs e)
        {
            dt_log.Clear();
            panel5.Controls.Clear();
            panel2.Visible = false;
            qIndex = 0;

            this.lab_tishi.Text = string.Format("考生：{0} 你好,你选择了模拟考试模式", _uis.Realname);
            this.btn_OK.Visible = true;
            this.panel5.Enabled = true;
            this.d_time.Visible = true;
            this.label1.Visible = false;
            this.label2.Visible = false;
            this.btn_OK.Visible = true;

            #region 模拟考试倒计时
            //Timer tmr = new Timer();
            tmr.Interval = 1000;//1秒1次
            this.d_time.Text = 45 + ":" + 00;
            tmr.Tick += new EventHandler(tmr_Tick);
            tmr.Start();
            #endregion

            dt_using = new DataTable();
            int[] a = new int[100];//已经出现过的随机数或者题号
            dt_using = _ib.GetErrorItem(_uis.Uid, 1);
            if (dt_using != null && dt_using.Rows.Count > 0)
            {
                for (int i = 0; i < dt_using.Rows.Count; i++)
                {
                    a[i] = int.Parse(dt_using.Rows[i]["tid"].ToString());
                }
                GetItem(a);
            }
            else
            {
                GetItem(a);
            }

            AddBtn();
            DisplayQuestion(dt_using);
            panel2.Visible = true;
            totaltime = DateTime.Now.AddMinutes(45);
        }

        /// <summary>
        /// 交卷
        /// </summary>
        private void btn_OK_Click(object sender, EventArgs e)
        {
            Complete();
            lockanswer();
        }
        #endregion

        #region 自定义方法

        /// <summary>
        /// 获取随机练习或者是模拟考试下的数据
        /// </summary>
        /// <param name="a">已经出现过的随机数或者题号数组</param>
        void GetItem(int[] a)
        {
            for (int alreadyitem = 0; alreadyitem < 100; alreadyitem++)//循环获取100道考题
            {
                int num = Common.GenNum.GetNum(itemcount);
                if (a.Contains(num))//判断生成的随机数是否已经出现过
                {
                    --alreadyitem;
                    continue;
                }
                dt_tiku = _ib.GetItemBank(2, num);
                dt_using.Merge(dt_tiku);
                a[alreadyitem] = num;//将符合条件的随机数添加的数组中
            }
        }

        /// <summary>
        /// 显示试题到窗体
        /// </summary>
        /// <param name="dt">题库</param>
        public bool DisplayQuestion(DataTable dt)
        {
            if (dt == null || dt.Rows.Count <= 0)
                return false;
            DataTable ddd = _ib.GeterrorRate(int.Parse(dt.Rows[qIndex]["tid"].ToString()));
            if (ddd != null && ddd.Rows.Count > 0)
                float.TryParse(ddd.Rows[0]["errorrate"].ToString(), out rate);
            this.label2.Text = rate == float.Parse("0") ? "0%" : (rate * 100 + "%");
            radioButton1.Checked = false;
            radioButton2.Checked = false;
            radioButton3.Checked = false;
            radioButton4.Checked = false;
            radioButton1.BackColor = Control.DefaultBackColor;
            radioButton2.BackColor = Control.DefaultBackColor;
            radioButton3.BackColor = Control.DefaultBackColor;
            radioButton4.BackColor = Control.DefaultBackColor;
            radioButton1.ForeColor = Control.DefaultForeColor;
            radioButton2.ForeColor = Control.DefaultForeColor;
            radioButton3.ForeColor = Control.DefaultForeColor;
            radioButton4.ForeColor = Control.DefaultForeColor;

            if (isAnswered())
            {
                lockanswer();

                if (isanswer)
                {
                    foreach (Control item in this.Controls["panel2"].Controls)
                    {
                        RadioButton rd = item as RadioButton;
                        if (rd == null) continue;
                        else
                        {
                            string b = "";
                            DataRow[] s = dt_log.Select(string.Format("tid={0}", dt.Rows[qIndex]["tid"].ToString()));

                            int a = int.Parse(s[0][0].ToString());

                            if (rd.Name.Split('n')[1].ToString() == s[0]["ZXDA"].ToString())
                            {
                                rd.Checked = true;
                                b = s[0]["isOK"].ToString();

                                if (b == "1")
                                {
                                    rd.BackColor = Color.Green;
                                    rd.ForeColor = Color.Yellow;
                                }
                                else
                                {
                                    rd.BackColor = Color.Red;
                                    rd.ForeColor = Color.Yellow;
                                }

                                textBox1.Text = qIndex + 1 + "、" + dt.Rows[qIndex]["itemcontent"].ToString();
                                if (dt.Rows[qIndex]["itemtype"].ToString() == "1")
                                {
                                    radioButton1.Visible = true;
                                    radioButton2.Visible = true;
                                    radioButton3.Visible = true;
                                    radioButton4.Visible = true;
                                    radioButton1.Text = dt.Rows[qIndex]["answer_a"].ToString();
                                    radioButton2.Text = dt.Rows[qIndex]["answer_b"].ToString();
                                    radioButton3.Text = dt.Rows[qIndex]["answer_c"].ToString();
                                    radioButton4.Text = dt.Rows[qIndex]["answer_d"].ToString();
                                }
                                else
                                {
                                    radioButton1.Text = dt.Rows[qIndex]["answer_y"].ToString();
                                    radioButton2.Text = dt.Rows[qIndex]["answer_n"].ToString();
                                    radioButton3.Visible = false;
                                    radioButton4.Visible = false;
                                }
                                return true;
                            }
                        }
                    }
                }

            }

            {
                unlockanswer();

                if (dt == null || dt.Rows.Count == 0)
                {
                    textBox1.Text = "";
                    radioButton1.Visible = false;
                    radioButton2.Visible = false;
                    radioButton3.Visible = false;
                    radioButton4.Visible = false;
                    MessageBox.Show("不错啊~~你居然还没有做错过呢！");
                    return false;
                }

                if (qIndex >= itemcount)
                    return false;
                textBox1.Text = qIndex + 1 + "、" + dt.Rows[qIndex]["itemcontent"].ToString();

                if (dt.Rows[qIndex]["itemtype"].ToString() == "1")
                {
                    radioButton1.Visible = true;
                    radioButton2.Visible = true;
                    radioButton3.Visible = true;
                    radioButton4.Visible = true;

                    radioButton1.Text = dt.Rows[qIndex]["answer_a"].ToString();
                    radioButton2.Text = dt.Rows[qIndex]["answer_b"].ToString();
                    radioButton3.Text = dt.Rows[qIndex]["answer_c"].ToString();
                    radioButton4.Text = dt.Rows[qIndex]["answer_d"].ToString();
                    thisanswer = dt.Rows[qIndex]["ZQDA"].ToString();


                    return true;
                }
                else
                {
                    radioButton1.Visible = true;
                    radioButton2.Visible = true;
                    radioButton3.Visible = false;
                    radioButton4.Visible = false;

                    radioButton1.Text = dt.Rows[qIndex]["answer_y"].ToString();
                    radioButton2.Text = dt.Rows[qIndex]["answer_n"].ToString();
                    thisanswer = dt.Rows[qIndex]["ZQDA"].ToString();

                    return true;
                }
            }
        }

        public bool NextQuestion()
        {
            if (qIndex + 1 >= dt_using.Rows.Count)
                return false;

            qIndex += 1;
            return DisplayQuestion(dt_using);

        }

        public bool BeforeQuestion()
        {
            if (qIndex <= 0)
                return false;
            qIndex -= 1;
            return DisplayQuestion(dt_using);
        }

        public void verifyAnswer(object sender, EventArgs e)
        {
            lockanswer();
            if (isAnswered()) changebtncolor((qIndex + 1).ToString());

            RadioButton r = sender as RadioButton;


            if (!r.Checked || isanswer) return;
            if (int.Parse(thisanswer) <= 4 && r.Name.Split('n')[1] == thisanswer)
            {
                r.BackColor = Color.Green;
                r.ForeColor = Color.Yellow;

                _ib.InsertErrorItem(_uis.Uid, int.Parse(dt_using.Rows[qIndex][0].ToString()), 1);

                dt_log.Rows.Add(new object[] { dt_using.Rows[qIndex]["tid"], r.Name.Split('n')[1], 1 });
                changebtncolor((qIndex + 1).ToString());
                return;
            }
            else if (int.Parse(thisanswer) <= 4 && r.Name.Split('n')[1] != thisanswer)
            {
                r.BackColor = Color.Red;
                r.ForeColor = Color.Yellow;

                _ib.InsertErrorItem(_uis.Uid, int.Parse(dt_using.Rows[qIndex][0].ToString()));

                dt_log.Rows.Add(new object[] { dt_using.Rows[qIndex]["tid"], r.Name.Split('n')[1], 0 });
                changebtncolor((qIndex + 1).ToString());
                return;
            }

            if (int.Parse(thisanswer) > 4 && r.Name.Split('n')[1] == (int.Parse(thisanswer) - 4).ToString())
            {
                r.BackColor = Color.Green;
                r.ForeColor = Color.Yellow;

                _ib.InsertErrorItem(_uis.Uid, int.Parse(dt_using.Rows[qIndex][0].ToString()), 1);

                dt_log.Rows.Add(new object[] { dt_using.Rows[qIndex]["tid"], r.Name.Split('n')[1], 1 });
                changebtncolor((qIndex + 1).ToString());
                return;
            }
            else if (int.Parse(thisanswer) > 4 && r.Name.Split('n')[1] != (int.Parse(thisanswer) - 4).ToString())
            {
                r.BackColor = Color.Red;
                r.ForeColor = Color.Yellow;

                _ib.InsertErrorItem(_uis.Uid, int.Parse(dt_using.Rows[qIndex][0].ToString()));

                dt_log.Rows.Add(new object[] { dt_using.Rows[qIndex]["tid"], r.Name.Split('n')[1], 0 });
                changebtncolor((qIndex + 1).ToString());
                return;
            }
        }

        public void changebtncolor(string id)
        {
            if (panel5.Controls.Count == 0) return;

            foreach (Control item in panel5.Controls)
            {
                Button btn = item as Button;
                if (btn != null && btn.Name == "ks_btn_" + id)
                {
                    btn.BackColor = Color.Yellow;
                }
            }
        }

        /// <summary>
        /// 锁定单选控件
        /// </summary>
        public void lockanswer()
        {
            radioButton1.Enabled = false;
            radioButton2.Enabled = false;
            radioButton3.Enabled = false;
            radioButton4.Enabled = false;
        }

        /// <summary>
        /// 解锁单选控件
        /// </summary>
        public void unlockanswer()
        {
            radioButton1.Enabled = true;
            radioButton2.Enabled = true;
            radioButton3.Enabled = true;
            radioButton4.Enabled = true;
        }

        /// <summary>
        /// 该题是否做过
        /// </summary>
        /// <returns></returns>
        public bool isAnswered()
        {
            DataRow[] dr = dt_log.Select(string.Format("tid={0}", dt_using.Rows[qIndex]["tid"].ToString()));
            if (dr == null || dr.Count() == 0)
            {
                isanswer = false;
                return false;
            }
            else
            {
                isanswer = true;
                return true;
            }
            //foreach (DataRow dr in dt_log.Rows)
            //{
            //    dt_log.
            //    if (dt_using.Rows[qIndex]["tid"].ToString() == dr["tid"].ToString())
            //    {
            //        isanswer = true;
            //        return true;
            //    }
            //    else
            //    {
            //        isanswer = false;
            //        return false;
            //    }
            //}
            return false;
        }

        public Button GenBtn(int id)
        {
            Button b = new Button();
            b.Name = "ks_btn_" + id.ToString();
            b.Text = id.ToString();
            b.Click += b_Click;
            b.Height = 35;
            b.Width = 35;
            b.FlatStyle = FlatStyle.Flat;
            //b.BackColor = Color.Green;
            //b.ForeColor = Color.White;

            if ((id - 1) < 20)
            {
                b.Location = new Point(36 * (id - 1), 0);
            }
            else if (20 <= (id - 1) && (id - 1) < 40)
            {
                b.Location = new Point(36 * (id - 21), 36);
            }
            else if (40 <= (id - 1) && (id - 1) < 60)
            {
                b.Location = new Point(36 * (id - 41), 36 * 2);
            }
            else if (60 <= (id - 1) && (id - 1) < 80)
            {
                b.Location = new Point(36 * (id - 61), 36 * 3);
            }
            else if (80 <= (id - 1) && (id - 1) < 100)
            {
                b.Location = new Point(36 * (id - 81), 36 * 4);
            }
            return b;
        }

        void b_Click(object sender, EventArgs e)
        {
            Button a = sender as Button;



            qIndex = int.Parse(a.Text) - 1;

            //if (!isAnswered()) a.BackColor = Color.Yellow;

            DisplayQuestion(dt_using);
        }

        /// <summary>
        /// 为模拟考试添加考题的btn按钮
        /// </summary>
        public void AddBtn()
        {
            for (int i = 0; i < 100; i++)
            {
                panel5.Controls.Add(GenBtn(i + 1));
            }
        }

        /// <summary>
        /// 到达设定时间后自动交卷事件
        /// </summary>
        void tmr_Tick(object sender, EventArgs e)
        {
            this.d_time.Text = (totaltime - DateTime.Now).ToString().Substring(3, 5);
            if (this.d_time.Text.Contains("00:00"))
            {
                tmr.Stop();
                Complete();
            }
        }

        /// <summary>
        /// 点击交卷按钮或者考试时间已到时调用
        /// </summary>
        void Complete()
        {
            tmr.Stop();
            DataRow[] dr = dt_log.Select("isok=1");
            MessageBox.Show("你此次考试得分：" + dr.Count().ToString());
            this.panel5.Enabled = false;
        }
        #endregion
    }
}
